<?php
namespace Api\Controller;

use Think\Controller;
use Think\Log;

class BaseController extends Controller
{

    const MICRO_APP = 'micro_app';

    protected $_data = array();

    function _initialize()
    {
        
        /**
         * 请求数据格式
         * data : base64
         * sign : 签名
         * timestamp : 时间戳
         */
        $data = I('data');
        $sign = I('sign');
        $timestamp = I('timestamp');
        $key = md5(BaseController::MICRO_APP);
        if ($this->verifySign($data, $sign, $key, $timestamp)) {
            $this->_data = json_decode(base64_decode($data), true);
        } else {
            // 检验出错
            $this->result(1000, array(), '数据有误');
        }
    }

    function result($status = 0, $data = array(), $msg = '请求成功')
    {
        if (! empty($data)) {
            $key = md5(BaseController::MICRO_APP);
            $data = $this->sign($data, $key);
        }
        $result = array();
        $result['status'] = $status;
        $result['msg'] = $msg;
        $result['data'] = $data;
        $this->ajaxReturn($result);
    }

    function checkToken()
    {
        $token = $this->_data['token'];
        if (empty($token)) {
            $this->result(2000, array(), '无权限访问');
        }
        $brokerToken = D('BrokerToken')->where(array(
            'token' => $token
        ))
            ->relation(true)
            ->find();
        if (empty($brokerToken)) {
            $this->result(2001, array(), '无权限访问');
        }
        $broker = $brokerToken['broker'];
        if ($broker['is_active'] == 0) {
            $this->result(1000, array(), '账号未激活');
        }
        if ($broker['broker_time'] < TIMESTAMP) {
            $this->result(1000, array(), '账号已过期');
        }
        return $broker;
    }

    /**
     *
     * @param unknown $data            
     */
    function sign($data, $key)
    {
        $json = json_encode($data);
        $encode = base64_encode($json);
        $timestamp = TIMESTAMP;
        $sign = hash_hmac('md5', $encode, $key . $timestamp);
        return array(
            'data' => $encode,
            'timestamp' => $timestamp,
            'sign' => $sign
        );
    }

    function verifySign($data, $sign, $key, $timestamp)
    {
        return hash_hmac('md5', $data, $key . $timestamp) == $sign;
    }
}

